package api

import (
	"github.com/gin-gonic/gin"
	"hcy-api/lib/http"
	"hcy-api/structs/enum"
	"hcy-api/structs/idp"
	"hcy-api/structs/tables"
	"idp/global"
	"idp/repository"
	"idp/service"
	"time"
)

var TaskApi = new(taskApi)

type taskApi struct {
}

func (api taskApi) Add(c *gin.Context) {
	var in idp.AddTaskDto
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	if in.EndTime <= time.Now().Unix() {
		http.BadWithCode(c, enum.ErrorMap.TaskTimeInvalid)
		return
	}
	self := http.GetCurrentUser(c)
	err := service.TaskService.AddTask(in, *self)
	if err != nil {
		http.BadWithCode(c, enum.ErrorMap.PullTaskError)
		return
	}
	http.OK204(c)
}

func (api taskApi) Page(c *gin.Context) {
	var in idp.SearchTaskDto
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	li, total, err := repository.TaskRepository.FindPage(in)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.OkPage(c, li, total)
}

func (api taskApi) StopTask(c *gin.Context) {
	in := struct {
		Id int64 `uri:"id"`
	}{}
	if err := c.ShouldBindUri(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	err := repository.TaskRepository.UpdateTaskExpiredById(in.Id, tables.IdpTaskStatusForAdminShutdown)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	global.TaskCatch.Delete(in.Id)
	http.OK204(c)
}

func (api taskApi) CountResult(c *gin.Context) {
	in := struct {
		Id int64 `uri:"id"`
	}{}
	if err := c.ShouldBindUri(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	r, err := service.TaskService.CountResult(in.Id)
	if err != nil {
		http.BadWithCode(c, enum.ErrorMap.GetReportErr)
		return
	}
	http.Ok(c, r)
}
